//
//  MyMapViewController.m
//  FoodCorner
//
//  Created by apple on 16/3/5.
//  Copyright © 2016年 zhangchao. All rights reserved.
//

#import "MyMapViewController.h"
#import "MyMapView.h"

//#define kWidth self.view.frame.size.width
//#define Height self.view.frame.size.width

@interface MyMapViewController ()<BMKGeneralDelegate,BMKMapViewDelegate,BMKLocationServiceDelegate,BMKPoiSearchDelegate>

@property (nonatomic, strong) MyMapView *myMapView;

@end

@implementation MyMapViewController
-(void)loadView
{
    _myMapView = [[MyMapView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = _myMapView;
}

- (void)setUpMapView
{
    _mapManager = [[BMKMapManager alloc] init];
    BOOL ret = [_mapManager start:@"DxMjYqusRA5R8SjoGy5Mz8av" generalDelegate:self];
    if (!ret) {
        NSLog(@"Set mapManager fail !");
    }
    
    //设置MapView
    _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 100, self.myMapView.frame.size.width, self.myMapView.frame.size.height-100)];
    _mapView.mapType = BMKMapTypeStandard;
    CLLocationCoordinate2D mapViewCenterCoordinate;
    mapViewCenterCoordinate.latitude = 39.915;
    mapViewCenterCoordinate.longitude = 116.404;
    _mapView.centerCoordinate = mapViewCenterCoordinate;
    _mapView.zoomLevel = 13;
    [self.myMapView addSubview:_mapView];
    
    self.classifyBtn = [UIButton buttonWithType:(UIButtonTypeRoundedRect)];
    self.classifyBtn.frame = CGRectMake(self.view.frame.size.width*0.75, self.view.frame.size.height*0.8, 70, 70);
    [self.classifyBtn.layer setCornerRadius:35];
    [self.classifyBtn.layer setMasksToBounds:YES];
    self.classifyBtn.backgroundColor = [UIColor blueColor];
    [self.classifyBtn setTitle:@"清除标记" forState:(UIControlStateNormal)];
    [self.classifyBtn setTintColor:[UIColor yellowColor]];
    [self.classifyBtn addTarget:self action:@selector(clickClassifyButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:self.classifyBtn];
}

- (void)setUpLocation
{
    _locationService = [[BMKLocationService alloc] init];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpMapView];
    [self setUpLocation];
    
    [self.myMapView.startLocationBtn addTarget:self action:@selector(clickStartLocationButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.myMapView.startSearchBtn addTarget:self action:@selector(clickStartPoiSearchButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.myMapView.nextPageBtn addTarget:self action:@selector(clickNextPageButton:) forControlEvents:(UIControlEventTouchUpInside)];
}

- (void)clickStartLocationButton:(UIButton *)sender
{
    _locationService.delegate = self;
    [_locationService startUserLocationService];
    //设定定位显示
    [_mapView setShowsUserLocation:YES];
    //设定定位数据更新
    CLLocationDistance locationDistance = 5;
    _locationService.distanceFilter = locationDistance;
}

//实现BMKLocationServiceDelegate协议
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
    _mapView.centerCoordinate = userLocation.location.coordinate;
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    _userLocation = [[BMKUserLocation alloc] init];
    _userLocation = userLocation;
}

- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"定位失败，错误代码：%ld",error.code);
}

- (void)clickClassifyButton:(UIButton *)sender
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    
    _currentPage = 0;
    
//    if (self.busRouteSearchBtn.hidden == NO) {
//        [self.classifyBtn setUserInteractionEnabled:NO];
//    }
//    
//    self.busRouteSearchBtn = [[UIButton alloc] init];
//    self.busRouteSearchBtn.frame = CGRectMake(self.classifyBtn.frame.origin.x-60, self.classifyBtn.frame.origin.y, 50, 50);
//    [self.busRouteSearchBtn setTitle:@"公交" forState:(UIControlStateNormal)];
//    [self.busRouteSearchBtn setTintColor:[UIColor yellowColor]];
//    self.busRouteSearchBtn.backgroundColor = [UIColor blueColor];
//    [self.busRouteSearchBtn.layer setMasksToBounds:YES];
//    [self.busRouteSearchBtn.layer setCornerRadius:25];
//    [self.busRouteSearchBtn addTarget:self action:@selector(clickBusRouteSearchButton:) forControlEvents:(UIControlEventTouchUpInside)];
//    self.busRouteSearchBtn.titleLabel.font = [UIFont systemFontOfSize:14];
//    self.busRouteSearchBtn.alpha = 0.6;
//    
//    self.walkRouteSearchBtn = [[UIButton alloc] init];
//    self.walkRouteSearchBtn.frame = CGRectMake(self.classifyBtn.frame.origin.x, self.classifyBtn.frame.origin.y-60, 50, 50);
//    [self.walkRouteSearchBtn setTitle:@"步行" forState:(UIControlStateNormal)];
//    [self.walkRouteSearchBtn setTintColor:[UIColor yellowColor]];
//    self.walkRouteSearchBtn.backgroundColor = [UIColor blueColor];
//    [self.walkRouteSearchBtn.layer setMasksToBounds:YES];
//    [self.walkRouteSearchBtn.layer setCornerRadius:25];
//    [self.walkRouteSearchBtn addTarget:self action:@selector(clickWalkRouteSearchButton:) forControlEvents:(UIControlEventTouchUpInside)];
//    self.walkRouteSearchBtn.titleLabel.font = [UIFont systemFontOfSize:14];
//    self.walkRouteSearchBtn.alpha = 0.6;
//    
//    self.clearOldMarkBtn = [UIButton buttonWithType:(UIButtonTypeRoundedRect)];
//    self.clearOldMarkBtn.frame = CGRectMake(self.classifyBtn.frame.origin.x-60, self.classifyBtn.frame.origin.y-60, 50, 50);
//    [self.clearOldMarkBtn.layer setCornerRadius:25];
//    [self.clearOldMarkBtn.layer setMasksToBounds:YES];
//    self.clearOldMarkBtn.backgroundColor = [UIColor blueColor];
//    [self.clearOldMarkBtn setTitle:@"清理" forState:(UIControlStateNormal)];
//    [self.clearOldMarkBtn setTintColor:[UIColor yellowColor]];
//    [self.clearOldMarkBtn addTarget:self action:@selector(removeOldMark:) forControlEvents:(UIControlEventTouchUpInside)];
//    self.clearOldMarkBtn.alpha = 0.6;
//    
//    [self.view addSubview:self.busRouteSearchBtn];
//    [self.view addSubview:self.walkRouteSearchBtn];
//    [self.view addSubview:self.clearOldMarkBtn];
//    
//    self.routeSearch = [[BMKRouteSearch alloc] init];
//    self.routeSearch.delegate = self;
}

- (void)clickStartPoiSearchButton:(UIButton *)sender
{
    _PoiSearch = [[BMKPoiSearch alloc] init];
    _PoiSearch.delegate = self;
    
    _currentPage = 0;
    
    BMKNearbySearchOption *nearbySearchOption = [[BMKNearbySearchOption alloc] init];
    CLLocationCoordinate2D coor = _userLocation.location.coordinate;
    nearbySearchOption.location = coor;
    nearbySearchOption.keyword = self.myMapView.inputTargetTF.text;
    nearbySearchOption.pageCapacity = 10;
    nearbySearchOption.radius = 1000;
    nearbySearchOption.pageIndex = _currentPage;
    BOOL flag = [_PoiSearch poiSearchNearBy:nearbySearchOption];
    if (flag) {
        NSLog(@"周边检索发送成功");
    }else{
        NSLog(@"周边检索发送失败");
    }
}

- (void)clickNextPageButton:(UIButton *)sender
{
    _currentPage++;
    BMKNearbySearchOption *nearbySearchOption = [[BMKNearbySearchOption alloc] init];
    CLLocationCoordinate2D coor = _userLocation.location.coordinate;
    nearbySearchOption.location = coor;
    nearbySearchOption.keyword = self.myMapView.inputTargetTF.text;
    nearbySearchOption.pageCapacity = 10;
    nearbySearchOption.radius = 1000;
    nearbySearchOption.pageIndex = _currentPage;
    BOOL flag = [_PoiSearch poiSearchNearBy:nearbySearchOption];
    if (flag) {
        NSLog(@"周边再次检索发送成功");
    }else{
        NSLog(@"周边再次检索发送失败");
    }
}

//在地图上显示检索结果
- (void)onGetPoiResult:(BMKPoiSearch*)searcher result:(BMKPoiResult*)poiResult errorCode:(BMKSearchErrorCode)errorCode{
//    NSLog(@"%u",errorCode);
    if (errorCode == BMK_SEARCH_NO_ERROR) {
        for (int i = 0; i < [poiResult.poiInfoList count]; i++) {
            BMKPointAnnotation *pointAnnotation = [[BMKPointAnnotation alloc] init];
            CLLocationCoordinate2D coor;
            BMKPoiInfo *poiInfo = [[BMKPoiInfo alloc] init];
            poiInfo = poiResult.poiInfoList[i];
            coor = poiInfo.pt;
            pointAnnotation.coordinate = coor;
            pointAnnotation.title = poiInfo.name;
            [_mapView addAnnotation:pointAnnotation];
        }
    }else if (errorCode == BMK_SEARCH_AMBIGUOUS_KEYWORD){
        NSLog(@"起始点有歧义");
    }else{
        NSLog(@"未找到结果");
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"周边未搜索到检索内容" message:@"请检查输入" preferredStyle:(UIAlertControllerStyleActionSheet)];
        UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"知道了" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertC addAction:alertA];
        [self presentViewController:alertC animated:YES completion:nil];
    }
}

//- (NSString *)getReverseGeoCode:(CLLocationCoordinate2D)cender
//{
//    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[
//    BMKReverseGeoCodeOption alloc]init];
//    reverseGeoCodeSearchOption.reverseGeoPoint = cender;
//    BOOL flag = [_codeSearch reverseGeoCode:reverseGeoCodeSearchOption];
//    if(flag)
//    {
//        return <#expression#>
//    }
//    else
//    {
//      NSLog(@"反geo检索发送失败");
//    }
//}
//
//- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
//{
//    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
//    [_mapView removeAnnotations:array];
//    array = [NSArray arrayWithArray:_mapView.overlays];
//    [_mapView removeOverlays:array];
//    if (error == 0) {
//        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
//        item.coordinate = result.location;
//        item.title = result.address;
//        [_mapView addAnnotation:item];
//        _mapView.centerCoordinate = result.location;
//        NSString* titleStr;
//        NSString* showmeg;
//        titleStr = @"反向地理编码";
//        showmeg = [NSString stringWithFormat:@"%@",item.title];
//        
////        UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:titleStr message:showmeg delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
////        [myAlertView show];
//    }
//}

//- (void)clickBusRouteSearchButton:(UIButton *)sender
//{
//    self.busRouteSearchBtn.hidden = YES;
//    self.walkRouteSearchBtn.hidden = YES;
//    self.clearOldMarkBtn.hidden = YES;
//    [self.classifyBtn setUserInteractionEnabled:YES];
//    
//    //设置起始与终点
//    BMKPlanNode *startNode = [[BMKPlanNode alloc] init];
//    startNode.pt = _userLocation.location.coordinate;
//    BMKPlanNode *endNode = [[BMKPlanNode alloc] init];
//    endNode.name = self.myMapView.inputTargetTF.text;
//    //设置路线规划策略
//    BMKTransitRoutePlanOption *transitRoutePlanOption = [[BMKTransitRoutePlanOption alloc] init];
//    transitRoutePlanOption.transitPolicy = BMK_TRANSIT_TIME_FIRST;
//    transitRoutePlanOption.from = startNode;
//    transitRoutePlanOption.to = endNode;
//    //开始搜索
//    BOOL flag = [_routeSearch transitSearch:transitRoutePlanOption];
//    if (flag) {
//        NSLog(@"路线规划发送成功");
//    }else{
//        NSLog(@"路线规划发送失败");
//    }
//}

//- (void)onGetTransitRouteResult:(BMKRouteSearch*)searcher result:(BMKTransitRouteResult*)result errorCode:(BMKSearchErrorCode)error
//{
//    if (error == BMK_SEARCH_NO_ERROR) {
//        NSLog(@"%@",result.taxiInfo);
//    }else{
//        NSLog(@"%u",error);
//    }
//}
//
//- (void)clickWalkRouteSearchButton:(UIButton *)sender
//{
//    self.busRouteSearchBtn.hidden = YES;
//    self.walkRouteSearchBtn.hidden = YES;
//    self.clearOldMarkBtn.hidden = YES;
//    [self.classifyBtn setUserInteractionEnabled:YES];
//}

//- (void)removeOldMark:(UIButton *)sender
//{
//    self.busRouteSearchBtn.hidden = YES;
//    self.walkRouteSearchBtn.hidden = YES;
//    self.clearOldMarkBtn.hidden = YES;
//    [self.classifyBtn setUserInteractionEnabled:YES];
//    
//    NSMutableArray *oldMarkArray = [NSMutableArray arrayWithArray:_mapView.annotations];
//    [_mapView removeAnnotations:oldMarkArray];
//    oldMarkArray = [NSMutableArray arrayWithArray:_mapView.overlays];
//    [_mapView removeOverlays:oldMarkArray];
//    
//}

- (void)viewWillAppear:(BOOL)animated
{
    _mapView.delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated
{
    _mapView.delegate = nil;
    _locationService.delegate = nil;
    _PoiSearch.delegate = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
